import fs from 'fs'
import path from 'path';
import { isValidToken } from './check';
import { Error, Success } from './interface';

function readTrashData(): any[] {
    const trashFilePath = path.join(__dirname, 'trash.json');
    
    try {
        const trashFileContent = fs.readFileSync(trashFilePath, { encoding: 'utf8' });
        return JSON.parse(trashFileContent);
    } catch {
        return [];
    }
}

export const trashEmpty = (token: string, quizIds: number[]): Success | Error => {
    const authUserId = isValidToken(token);
    const trashData = readTrashData();

    if (!authUserId) {
        return { error: 'Token is empty or invalid (does not refer to valid logged in user session)' };
    }

    quizIds.forEach(quizId => {
        if (!trashData.some(quiz => quiz.QuizID === quizId)) {
            return { error: 'One or more of the Quiz IDs is not currently in the trash' };
        } else if (!trashData.some(quiz => quiz.QuizID === quizId && quiz.AuthorID === authUserId)) {
            return { error: 'Quiz ID does not refer to a quiz that this user owns.' };
        }
    });

    const updatedTrashData = trashData.filter(quiz => !quizIds.includes(quiz.QuizID) || quiz.AuthorID !== authUserId);

    fs.writeFileSync('./trash.json', JSON.stringify(updatedTrashData, null, 2));

    return { message: 'Success!' };
};